<template>
  <div class="app-container">
    <el-row :gutter="10">
      <el-col :span="8">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              >新增</el-button
            >
          </el-col>
        </el-row>

        <el-card style="height: calc(100vh - 125px)">
          <div slot="header">
            <span><i class="el-icon-collection"></i> 一级类别</span>
            <el-button
              style="float: right; padding: 3px 0"
              type="text"
              icon="el-icon-refresh-right"
              @click="refreshCacheNames"
            ></el-button>
          </div>
          <el-table
            v-loading="loading"
            :data="fitstList"
            :height="tableHeight"
            highlight-current-row
            style="width: 100%"
            @row-click="getRowCategory"
            ref="firstTableRef"
          >
            <el-table-column
              label="序号"
              width="60"
              type="index"
            ></el-table-column>
            <el-table-column
              label="一级分类"
              align="center"
              prop="categoryName"
              :show-overflow-tooltip="true"
            >
              <template slot-scope="scope">
                {{ scope.row.categoryName }}({{ scope.row.association.length }})
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              width="60"
              align="center"
              class-name="small-padding fixed-width"
            >
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate(scope.row)"
                ></el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>

      <el-col :span="16">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd2()"
              >新增</el-button
            >
          </el-col>
        </el-row>

        <el-card style="height: calc(100vh - 125px)">
          <div slot="header">
            <span><i class="el-icon-collection"></i> 标识类别</span>
          </div>
          <el-table
            :data="categoryList"
            row-key="categoryId"
            :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
            @selection-change="handleSelectionChange"
            :height="tableHeight"
          >
            <el-table-column
              type="index"
              label="序号"
              width="55"
              align="center"
            >
              <template slot-scope="scope">
                {{ scope.row.indexx }}
              </template>
            </el-table-column>

            <el-table-column
              label="标识名称"
              align="left"
              prop="categoryName"
            />
            <el-table-column
              label="创建时间"
              align="center"
              prop="createTime"
              width="180"
            >
            </el-table-column>
            <el-table-column
              label="创建人"
              align="center"
              prop="createBy"
              width="100"
            />
            <el-table-column
              label="操作"
              align="center"
              class-name="small-padding fixed-width"
            >
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate2(scope.row)"
                  v-hasPermi="['system:category:edit']"
                  >修改</el-button
                >
                <!--  v-if="scope.row.parentId == ''" -->
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-plus"
                  @click="handleAdd2(scope.row)"
                  v-hasPermi="['system:category:add']"
                  >新增</el-button
                >
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete2(scope.row)"
                  v-hasPermi="['system:category:remove']"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 一级类目 -->
    <el-dialog
      :title="title"
      :visible.sync="firstOpen"
      width="580px"
      append-to-body
      v-dialogDrag
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="分类名称" prop="categoryName">
              <el-input
                v-model="form.categoryName"
                placeholder="请输入分类名称"
              />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="二级类目" prop="association">
              <el-select
                multiple
                v-model="form.association"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="dict in categoryListCache"
                  :key="dict.categoryId"
                  :label="dict.categoryName"
                  :value="dict.categoryId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="显示排序" prop="px">
              <el-input-number
                v-model="form.px"
                controls-position="right"
                :min="0"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 二级类目 -->
    <el-dialog
      :title="title"
      :visible.sync="categoryOptn"
      width="600px"
      append-to-body
      v-dialogDrag
    >
      <el-form
        ref="categoryForm"
        :model="categoryForm"
        :rules="rules2"
        label-width="80px"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="上级类目">
              <treeselect
                v-model="categoryForm.parentId"
                :options="categoryOptions"
                :normalizer="normalizer"
                :show-count="true"
                placeholder="选择上级类目"
              />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item
              label="分类名称"
              prop="categoryName"
              style="width: 100%"
            >
              <el-input
                v-model="categoryForm.categoryName"
                placeholder="请输入分类名称"
              />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="显示排序" prop="px">
              <el-input-number
                v-model="categoryForm.px"
                controls-position="right"
                :min="0"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm2">确 定</el-button>
        <el-button @click="cancel2">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  firstListCategory,
  firstGetCategory,
  firstAddCategory,
  firstDelCategory,
  firstUpdateCategory,
} from "@/api/identity/category";
import {
  listCategory,
  getCategory,
  delCategory,
  addCategory,
  updateCategory,
  exportCategory,
  treeselectCategory,
} from "@/api/identity/category";

import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "category222",
  data() {
    return {
      loading: false,
      tableHeight: window.innerHeight - 200,
      fitstList: [],
      categoryList: [],
      categoryListCache: [],
      firstOpen: false,
      categoryOptn: false,
      title: "",
      form: {},
      rules: {
        categoryName: [
          { required: true, message: "标识名称不能为空", trigger: "blur" },
        ],
      },
      categoryOptions: [],

      // 表单参数
      categoryForm: {},
      // 表单校验
      rules2: {
        categoryName: [
          { required: true, message: "标识名称不能为空", trigger: "blur" },
        ],
        categoryPid: [
          {
            required: true,
            message: "标识所属分类id不能为空",
            trigger: "blur",
          },
        ],
        categoryCreatetime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" },
        ],
        categoryCreateuser: [
          { required: true, message: "创建人不能为空", trigger: "blur" },
        ],
      },
    };
  },
  components: {
    Treeselect,
  },
  created() {
    this.getFirstList();
    this.getCategoryList();
  },
  methods: {
    /** 查询缓存名称列表 */
    getFirstList() {
      this.loading = true;
      firstListCategory().then((response) => {
        this.fitstList = response.data.map((item) => {
          item.association =
            item.association.slice(0, -1) != ""
              ? item.association
                  .slice(0, -1)
                  .split(",")
                  .map((i) => (i ? Number(i) : undefined))
              : [];
          return item;
        });
        console.log(" this.fitstList : ", this.fitstList);

        this.loading = false;
      });
    },
    /** 查询列表 */
    getCategoryList() {
      listCategory(this.queryParams).then((response) => {
        // response.data.map((item) => {
        //   if (item.parentId == 0 && !item.parentName) {
        //     item.parentName = item.categoryName;
        //     item.categoryName = null;
        //   }
        // });
        this.categoryListCache = this.handleTree(response.data, "categoryId");
        this.categoryList = this.handleTree(response.data, "categoryId").map(
          (item, i) => {
            item.indexx = i + 1;
            item.children &&
              item.children.forEach((c, d) => {
                var a = d + 1;
                c.indexx = item.indexx + "." + a;
              });
            return item;
          }
        );
        console.log(" this.categoryList: ", this.categoryList);
      });
    },
    /** 查询缓存键名列表 */
    getRowCategory(row) {
      this.categoryList = this.categoryListCache
        .filter((item) => {
          return row.association.includes(item.categoryId);
        })
        .map((item, i) => {
          item.indexx = i + 1;
          item.children &&
            item.children.forEach((c, d) => {
              var a = d + 1;
              c.indexx = item.indexx + "." + a;
            });
          return item;
        });
    },
    refreshCacheNames() {
      this.$refs.firstTableRef.setCurrentRow();
      this.categoryList = this.categoryListCache.map((item, i) => {
        item.indexx = i + 1;
        item.children &&
          item.children.forEach((c, d) => {
            var a = d + 1;
            c.indexx = item.indexx + "." + a;
          });
        return item;
      });
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.firstOpen = true;
      this.title = "添加一级类别";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const categoryId = row.categoryId;
      firstGetCategory({ categoryId }).then((res) => {
        res.data.association =
          res.data.association.slice(0, -1) != ""
            ? res.data.association
                .slice(0, -1)
                .split(",")
                .map((i) => (i ? Number(i) : undefined))
            : [];
        this.form = res.data;
        console.log("this.form: ", this.form);
        this.firstOpen = true;
        this.title = "修改一级类别";
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.association.push(",");
          this.form.association = this.form.association.join(",");
          if (this.form.categoryId != null) {
            firstUpdateCategory(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.firstOpen = false;
              this.getFirstList();
            });
          } else {
            firstAddCategory(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.firstOpen = false;
              this.getFirstList();
            });
          }
        }
      });
    },
    // 取消按钮
    cancel() {
      this.firstOpen = false;
      this.reset();
    },
    // 取消按钮
    cancel2() {
      this.categoryOptn = false;
      this.reset2();
    },
    // 表单重置
    reset() {
      this.form = {
        categoryId: undefined,
        categoryName: "",
        px: 1,
        association: [],
      };
      this.resetForm("form");
    },
    // 表单重置
    reset2() {
      this.categoryForm = {
        categoryId: null,
        categoryName: null,
        categoryPid: null,
        categoryCreatetime: null,
        categoryCreateuser: null,
        categoryUpdatetime: null,
        categoryUpdateuser: null,
        px: 1,
      };
      this.resetForm("categoryForm");
    },
    handleDelete(row) {
      const categoryId = row.categoryId;
      const categoryName = row.categoryName;
      this.$confirm(
        '是否确认删除一级分类为"' + categoryName + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return firstDelCategory(categoryId);
        })
        .then(() => {
          this.getFirstList();
          this.msgSuccess("删除成功");
        })
        .catch(() => {});
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      console.log("selection: ", selection);
      this.ids = selection.map((item) => item.categoryId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    /** 新增按钮操作 */
    handleAdd2(row) {
      console.log("row: ", row);
      this.reset2();
      this.getTreeselect();
      if (row != null && row.categoryId) {
        this.categoryForm.parentId = row.categoryId;
      } else {
        this.categoryForm.parentId = 0;
      }
      this.categoryOptn = true;
      this.title = "新增标识分类";
    },
    /** 修改按钮操作 */
    handleUpdate2(row) {
      this.reset2();
      this.getTreeselect();
      const categoryId = row.categoryId || this.ids;
      getCategory(categoryId).then((response) => {
        this.categoryForm = response.data;
        this.categoryOptn = true;
        this.title = "修改标识分类";
      });
    },
    /** 提交按钮 */
    submitForm2() {
      this.$refs["categoryForm"].validate((valid) => {
        if (valid) {
          if (this.categoryForm.categoryId != null) {
            updateCategory(this.categoryForm).then((response) => {
              this.msgSuccess("修改成功");
              // this.categoryOptn = false;
              this.getCategoryList();
            });
          } else {
            addCategory(this.categoryForm).then((response) => {
              this.msgSuccess("新增成功");
              // this.categoryOptn = false;
              this.getCategoryList();
            });
          }
        }
      });
    },
    /** 查询菜单下拉树结构 */
    getTreeselect() {
      treeselectCategory().then((response) => {
        this.categoryOptions = [];
        const menu = { id: 0, label: "上级分类", children: [] };
        // menu.children = this.handleTree(response.data, "categoryId");
        // console.log('menu: ', menu);

        menu.children = response.data.map((item) => {
          // delete item.children;
          return item;
        });

        this.categoryOptions.push(menu);
        console.log("this.categoryOptions: ", this.categoryOptions);
      });
    },
    /** 删除按钮操作 */
    handleDelete2(row) {
      const categoryId = row.categoryId;
      const categoryName = row.categoryName;
      this.$confirm(
        '是否确认删除类目名称为"' + categoryName + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delCategory(categoryId);
        })
        .then(() => {
          this.getCategoryList();
          this.msgSuccess("删除成功");
        });
    },
    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.label,
        children: node.children,
      };
    },
  },
};
</script>
